package com.example.myapplication;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Button;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
public class MusicActivity extends AppCompatActivity {

    private Button buttonStart, buttonStop, buttonBind, buttonUnbind;
    private boolean isBound = false;
    private MyService.MyBinder binder;
    private ServiceConnection connection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            // We've bound to LocalService, cast the IBinder and get LocalService instance
            binder = (MyService.MyBinder) service;
            isBound = true;
            // Optionally call a method on the service here, like:
            // binder.getMyService().doSomething();
            // Start music playback through the bound service
            binder.getService().startMusic();
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            isBound = false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_music);

        buttonStart = findViewById(R.id.buttonStart);
        buttonStop = findViewById(R.id.buttonStop);
        buttonBind = findViewById(R.id.buttonBind);
        buttonUnbind = findViewById(R.id.buttonUnbind);

        Intent intent = new Intent(MusicActivity.this, MyService.class);

        buttonStart.setOnClickListener(v -> startService(intent));
        buttonStop.setOnClickListener(v -> stopService(intent));

        buttonBind.setOnClickListener(v -> bindService(intent, connection, Context.BIND_AUTO_CREATE));
        buttonUnbind.setOnClickListener(v -> {
            if (isBound) {
                // Unbind from the service
                unbindService(connection);
                isBound = false;
                // Optionally call a method on the service here to stop playback
                // if you haven't already
                // binder.getMyService().stopMusic();
            }
        });

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });
    }
}